﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Linq;
using Db4objects.Db4o;
using Db4objects.Db4o.Query;
using Db4objects.Db4o.Linq;
using MonthCalendar;
using System.IO;



namespace Yosca
{
	/// <summary>
	/// Interaction logic for InvoiceProfile.xaml
	/// </summary>
	public partial class InvoiceProfile : Window
	{
		//Printer stuff
			
		//IObjectContainer itemDb = Db4oFactory.OpenFile("ItemDb.db4o");
        IEnumerable<Item> itemList;
		Database dbase = Database.Instance;
		Invoice inv; 
		
		//Item tmpitm;
		public InvoiceProfile(Invoice profile)
		{
			this.InitializeComponent();
			// Insert code required on object creation below this point.
			inv = profile;
			
			updateFields(profile.defCust);			
			populateGrid();
            addHeaders();
			
		}
		
		 private void updateFields(Customer cust)
        {
			// populate page with customer information
            string[] fAndL = cust.name.Split(' ');
            fName.Content = fAndL[0];
            lName.Content = fAndL[1];
            invoiceNum.Content = inv.inv_num;
            bAddress.Content = cust.bAddress;
            bCity.Content = cust.bCity;
            bState.Content = cust.bState;
            bZip.Content = cust.bZip;
            jAddress.Content = inv.jAddress;
            jCity.Content = inv.jCity;
            jState.Content = inv.jState;
            jZip.Content = inv.jZip;
            hPhone.Content = cust.hPhone;
            cPhone.Content = cust.cPhone;
            email.Content = cust.email;
            website.Content = cust.website;
            result.Content = inv.getInvoiceStatus();
			totalBox.IsReadOnly = true;

            // add blackout dates
            estDate.BlackoutDates.Add(new CalendarDateRange(System.DateTime.MinValue, inv.estimateDate.AddDays(-1)));
            schedDate.BlackoutDates.Add(new CalendarDateRange(System.DateTime.MinValue, inv.estimateDate.AddDays(-1)));
            completedDate.BlackoutDates.Add(new CalendarDateRange(System.DateTime.MinValue, inv.estimateDate.AddDays(-1)));

            if (inv.completionDate != System.DateTime.MinValue)
                scheduleButton.Visibility = Visibility.Collapsed;
			// set estDate
			estDate.Text = inv.estimateDate.ToShortDateString();
			estDate.IsEnabled = false;
			// check if schedDate is set
			if(inv.scheduledDate != System.DateTime.MinValue)
			{
				schedDate.Text = inv.scheduledDate.ToShortDateString();
				schedDate.IsEnabled  = false;
			}
			// check if completionDate is set
			if(inv.completionDate != System.DateTime.MinValue)
			{
				completedDate.Text = inv.scheduledDate.ToShortDateString();
				completedDate.IsEnabled  = false;
			}
            if (inv.flags[0])
            {
                drive.IsChecked = true;
            }
            if (inv.flags[1])
            {
                other.IsChecked = true;
            }
            if (inv.flags[2])
            {
                think.IsChecked = true;
            }
            if (inv.flags[3])
            {
                high.IsChecked = true;
            }
            if (inv.flags[4])
            {
                talk.IsChecked = true;
            }
			
			
        }
		
		private void addHeaders(){
			//populate column headers and bind to data types
            invGrid.AutoGenerateColumns = false;
            invGrid.CanUserAddRows = false;
			invGrid.IsReadOnly = true;

			DataGridTextColumn lineNumCol = new DataGridTextColumn();
            lineNumCol.Header = "LINE #";
            lineNumCol.Binding = new Binding("lineNum");
            invGrid.Columns.Add(lineNumCol);
			
			DataGridTextColumn itemCol = new DataGridTextColumn();
            itemCol.Header = "ITEM";
            itemCol.Binding = new Binding("item");
            invGrid.Columns.Add(itemCol);
			
			DataGridTextColumn descriptCol = new DataGridTextColumn();
            descriptCol.Header = "DESCRIPTION";
            descriptCol.Binding = new Binding("description");
            invGrid.Columns.Add(descriptCol);
			
			DataGridTextColumn qtyCol = new DataGridTextColumn();
            qtyCol.Header = "QTY";
            qtyCol.Binding = new Binding("qty");
            invGrid.Columns.Add(qtyCol);
			
			DataGridTextColumn rateCol = new DataGridTextColumn();
            rateCol.Header = "RATE";
            rateCol.Binding = new Binding("rate");
			rateCol.Binding.StringFormat = "$0.00";
            invGrid.Columns.Add(rateCol);	
         

            
		}
		public void populateGrid(){
			// populate rows with Item information pertaining to the selected customer
			itemList =  from Item itm in dbase.db
				        where itm.invoiceNum == inv.inv_num
	                    select itm;
			invGrid.ItemsSource = itemList.ToList();
            totalBox.Text = "$" + getTotal();
           
		}

		private void closeClick(object sender, System.Windows.RoutedEventArgs e)
	    {
			Database invDB = Database.Instance;
            if ((bool)(drive.IsChecked))
            {
                inv.flags[0] = true;
            }
			else
			{
				inv.flags[0] = false;
			}
            if ((bool)(other.IsChecked))
            {
                inv.flags[1] = true;
            }
			else
			{
				inv.flags[1] = false;
			}
            if ((bool)(think.IsChecked))
            {
                inv.flags[2] = true;
            }
			else
			{
				inv.flags[2] = false;
			}
            if ((bool)(high.IsChecked))
            {
                inv.flags[3] = true;
            }
			else
			{
				inv.flags[3] = false;
			}
            if ((bool)(talk.IsChecked))
            {
                inv.flags[4] = true;
            }
			else
			{
				inv.flags[4] = false;
			}
            
			invDB.db.Store(inv);
			invDB.db.Commit();
		    this.Close();
		}

		private void enterClick(object sender, System.Windows.RoutedEventArgs e)
		{
			
			if(itemBox.Text == "" || descriptionBox.Text == "" || qtyBox.Text == "" || rateBox.Text == "$")
				MessageBox.Show("All text fields must be complete\nTry again");
			else{
				// create item
				Item itm = new Item();
				itm.invoiceNum = inv.inv_num;
				itm.item = itemBox.Text.ToUpper();
				itm.description = descriptionBox.Text.ToUpper();
				itm.qty = Convert.ToInt32(qtyBox.Text);
				itm.rate = Convert.ToDouble(rateBox.Text);
                //set line number  
                if (itemList != null) 
                {
                    itm.lineNum = itemList.Count() + 1;
                }
				// store item in dbase
				dbase.db.Store(itm);
				dbase.db.Commit();
				// reset fields
				itemBox.Text = "";
				descriptionBox.Text = "";
				qtyBox.Text = "";
				rateBox.Text = "";
				populateGrid();
                totalBox.Text = "$" + getTotal();
			}
		}
        private string getTotal() 
        {
            double total = 0.00;
			// sum up total
            if (itemList != null)
            {
                foreach (Item i in itemList)
                {
                    total += (i.rate * i.qty);
                }
            }
			// parse to x.xx format
			String totalStr = total.ToString();
			if (!totalStr.Contains("."))
				totalStr += ".00";
			else if (totalStr.Substring(totalStr.Length-1).Length == 1)
				totalStr += "0";
			String[] split = totalStr.Split('.');
			if (split[1].Length > 2)
				totalStr = totalStr.Substring(0, totalStr.Length-1);
			
            return totalStr;
        }

        private void printClick(object sender, System.Windows.RoutedEventArgs e)
        {
			this.Topmost = false;
			PrintEstimate page = new PrintEstimate(itemList, inv);
            page.Topmost = true;
            page.Show();
            page.printDoc();
            this.Topmost = true;        
        }

        private void emailClick(object sender, System.Windows.RoutedEventArgs e)
        {

            PrintEstimate document = new PrintEstimate(itemList, inv);
            emailClient mailClient = new emailClient(document, inv.defCust.email);
            this.Topmost = false;
            mailClient.Show();
        }


        private void statusClick(object sender, System.Windows.RoutedEventArgs e)
        {
        	InvStatus status = new InvStatus(inv, result);
			status.Show();					
        }

        private void scheduleClick(object sender, System.Windows.RoutedEventArgs e)
        {
           
                if (schedDate.IsEnabled && schedDate.SelectedDate != null)
                {
                    if (MessageBox.Show("Schedule appointment for " + ((System.DateTime)schedDate.SelectedDate).ToShortDateString() + "?", "Calendar", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                    {
                        AddAppointmentWindow aaw = new AddAppointmentWindow((System.DateTime)schedDate.SelectedDate, inv.inv_num);
                        inv.scheduledDate = (System.DateTime)schedDate.SelectedDate;
                        inv.invoiceStatus++; // invoice status is now job scheduled
                        result.Content = inv.getInvoiceStatus();
						dbase.db.Store(inv);
						dbase.db.Commit();
                        this.Topmost = false;
                        schedDate.IsEnabled = false;
                        aaw.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                        aaw.Show();
                    }
                }
                else if (completedDate.IsEnabled && completedDate.SelectedDate != null)
                {
                    if (MessageBox.Show("Schedule appointment for " + ((System.DateTime)completedDate.SelectedDate).ToShortDateString() + "?", "Calendar", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                    {
                        AddAppointmentWindow aaw = new AddAppointmentWindow((System.DateTime)completedDate.SelectedDate);
                        inv.completionDate = (System.DateTime)completedDate.SelectedDate;
						dbase.db.Store(inv);
						dbase.db.Commit();
                        this.Topmost = false;
                        completedDate.IsEnabled = false;
                        aaw.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                        aaw.Show();
                    }
                }
            
        }

        private void gmapClick(object sender, System.Windows.RoutedEventArgs e)
        {
            string target = "http://www.maps.google.com/?q=";
            string input = inv.jAddress + " " + inv.jCity + " " + inv.jZip;
            target += input;
            try
            {
                System.Diagnostics.Process.Start(target);
            }
            catch (System.ComponentModel.Win32Exception noBrowser)
            {
                if (noBrowser.ErrorCode == -2147467259)
                    MessageBox.Show(noBrowser.Message);
            }
            catch (System.Exception other)
            {
                MessageBox.Show(other.Message);
            }
        }

        






	}
}
